package com.itheima.sh.controller;

import com.itheima.sh.pojo.IpCount;
import com.itheima.sh.service.DockerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
public class DockerController {

    @Autowired
    private DockerService dockerService;

    @GetMapping("/hello")
    public void getIp(HttpServletRequest request, HttpServletResponse response){
        //定义一个计数器
        int count =1;
        //获取页面上访问的IP
        String ip = request.getRemoteHost();
        //先去数据库查询IP是否存在
        IpCount flag = dockerService.findByIp(ip);
        if(flag!=null){
             count =dockerService.getCount(ip);
            //如果访问地址IP已经在数据库存在 访问次数加一
            count +=1;
            //并且修改数据的IP访问次数
            dockerService.updateByIp(count,ip);
        }else{
            //如果数据库不存在该IP,就插入指定的IP地址
            dockerService.insertByIp(ip,count);
        }

        //处理响应乱码
        response.setContentType("text/html;charset=utf-8");
        try {
            response.getWriter().write(ip+"访问了"+count+"次！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
